package com.gandong8.trace.tool.config.redis;



import com.gandong8.trace.tool.config.GlobalProperties;
import com.gandong8.trace.tool.config.redis.properties.JedisProperties;
import com.gandong8.trace.tool.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableConfigurationProperties({JedisProperties.class, GlobalProperties.class})
@Slf4j
public class JedisConf {

    @Autowired
    private JedisProperties myProps;
    @Autowired
    private GlobalProperties globalProperties;

    @Bean(name = "jedisPool")
    @ConditionalOnMissingBean(JedisPool.class)
    public JedisPool createJedisPool() {
        if(!globalProperties.getJedisOpen()) {
            System.err.println("jedis not allowed");
            return null;
        }
        JedisPoolConfig config = createConfig();
        log.info("----redis start by jedis----");
        return new JedisPool(config, myProps.getHost(), myProps.getPort(), myProps.getTimeout(), myProps.getPassword());
    }

    private JedisPoolConfig createConfig(){
        if (myProps == null) {
            throw new GlobalException("redisProperties is null");
        }
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(myProps.getMaxIdle());
        config.setMinIdle(myProps.getMinIdle());
        config.setMaxTotal(myProps.getMaxTotal());
        config.setMaxWaitMillis(myProps.getMaxWaitMillis());
        config.setTestOnBorrow(myProps.getTestOnBorrow());
        config.setTestOnReturn(myProps.getTestOnReturn());
        config.setTestWhileIdle(myProps.getTestWhileIdle());
        return config;
    }
}
